/**
 * ReportGear(2011)
 */
package com.reportgear.report.model.script.function;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.abbp.report.model.cell.style.Style;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.reportgear.report.model.script.function.Function.Type;

/**
 * 报表函数管理器
 * 
 * @version 1.0 2011-5-2
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public enum FunctionManager {
	INSTANCE;

	// 函数容器
	private Map<Function.Type, List<Function>> fnMap = new HashMap<Function.Type, List<Function>>();
	private Logger logger = LoggerFactory.getLogger(Style.class.getName());

	FunctionManager() {
		this.initMap();
		this.registerAllFunctions();
	}

	// 初始化Map
	private void initMap() {
		this.fnMap.put(Type.MATH, new ArrayList<Function>());
		this.fnMap.put(Type.TEXT, new ArrayList<Function>());
		this.fnMap.put(Type.DATETIME, new ArrayList<Function>());
		this.fnMap.put(Type.ARRAY, new ArrayList<Function>());
	}

	// 注册所有函数
	private void registerAllFunctions() {
		this.registerFunction(new Sum());
		this.registerFunction(new Avg());
		this.registerFunction(new ToList());
		this.registerFunction(new GetCurrentDateTime());
		this.registerFunction(new GetCurrentDate());
	}

	/**
	 * 获取类型函数列表
	 * 
	 * @param type
	 *            类型
	 * @return 类型对应的函数列表
	 */
	public List<Function> getTypeList(Type type) {
		return this.fnMap.get(type);
	}

	// 获取函数列表
	public List<Function> getFunctionList() {
		List<Function> fnList = new ArrayList<Function>();

		fnList.addAll(this.getTypeList(Type.MATH));
		fnList.addAll(this.getTypeList(Type.TEXT));
		fnList.addAll(this.getTypeList(Type.DATETIME));
		fnList.addAll(this.getTypeList(Type.ARRAY));

		return fnList;
	}

	/**
	 * 注册函数
	 * 
	 * @param fn
	 *            需要注册的函数
	 */
	public void registerFunction(Function fn) {
		List<Function> fnList = this.getTypeList(fn.getType());

		if (fnList == null) {
			logger.warn("没有注册的函数分类:" + fn.getType());
		} else {
			fnList.add(fn);
		}
	}
}
